package com.elinkway.infinitemovies.shakead;

import android.app.Activity;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.elinkway.infinitemovies.adaction.CommonAdActionHandle;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.bean.NewAdDataBean;
import com.elinkway.infinitemovies.bean.ServerPayload;
import com.elinkway.infinitemovies.http.requesttask.RequestAdTask;
import com.elinkway.infinitemovies.selfdata.AdRequestStatis;
import com.elinkway.infinitemovies.selfdata.SelfDataConstant;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.le123.ysdq.R;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by huangxiaojian on 2017/7/31.
 *
 * 详情页摇晃 红包广告
 *
 * 可做成通用的类
 */

public class ShakeAd {

    public final String TAG = "ShakeAd";
    /**
     * 控制动画的停止，只要是
     * 动画被点击 或者
     * 跳出了首页 不管次数，回来不在展示动画
     */
    public final String NO_SHAKE_ANIMATION = "shakeAnimations";
    /**
     * 第二天展示动画的逻辑 标识第二天的缓存key
     */
    public final String NEXT_DAY_SHAKE_ANIMATION = "nextDayShakes";

    /**
     * 控制动画开始、停止的切换
     */
    private static boolean isStart = false;
    /**
     * 动画计时器
     */
    private Timer shakeAnimationTimer = null;
    /**
     * 控制动画开始的次数
     */
    private int shakeTime = 0;

    private Activity mActivity;

    public ShakeAd(Activity activity, View view) {
        mActivity = activity;
        initShakeView(view);
    }

    private FrameLayout adContainer;
    private SimpleDraweeView adIcon;
    private ImageView adTip;

    private void initShakeView(View view) {
        adContainer = (FrameLayout) view.findViewById(R.id.adContainer);
        adIcon = (SimpleDraweeView) view.findViewById(R.id.adIcon);
        adTip = (ImageView) view.findViewById(R.id.redTip);
    }

    private void showShakeAd(NewAdDataBean result) {
        if (null == result) {
            return;
        }

        final ServerPayload serverPayload = (ServerPayload) result.payload;
        if (null == serverPayload) {
            return;
        }
        String tipIcon = "";
        if (null != result.ext) {
            tipIcon = result.ext.badge;
        }
        if (MoviesUtils.isProductKuaiKan() || MoviesUtils.isProductYsdq()) {
            if (!StringUtil.isEmpty(serverPayload.pic)) {
                //重定向，需要清除缓存
                Fresco.getImagePipeline().clearCaches();
                ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
                    @Override
                    public void onFinalImageSet(
                            String id,
                            @Nullable ImageInfo imageInfo,
                            @Nullable Animatable anim) {
                        if (anim != null) {
                            // 其他控制逻辑
                            anim.start();
                        }
                    }
                };
                DraweeController controller = Fresco.newDraweeControllerBuilder()
                        .setUri(Uri.parse(serverPayload.pic))
                        .setControllerListener(controllerListener)
                        .build();
                adIcon.setController(controller);
            }

            if (!StringUtil.isEmpty(tipIcon)) {
                ImageLoader.getInstance().displayImage(tipIcon, adTip);
            }
            umengServerShow();
            adContainer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    umengServerClick();
                    stopShakeAnimation();
                    if (serverPayload.action == 1) {  //打开webView
                        CommonAdActionHandle.getInstance().go2WebView(mActivity, serverPayload.lp);
                    } else if (serverPayload.action == 2) {  //下载应用
                        CommonAdActionHandle.getInstance().downloadApp(mActivity, serverPayload.lp);
                    }
                }
            });

            boolean isNextDay = false;
            if (SharePreferenceManager.getVaule(mActivity, NEXT_DAY_SHAKE_ANIMATION, "0").equals("0") ||
                    isNextDayForShowShake(SharePreferenceManager.getVaule(mActivity, NEXT_DAY_SHAKE_ANIMATION, "0"), result.ts)) {
                isNextDay = true;
            }

            SharePreferenceManager.saveVaule(mActivity, NEXT_DAY_SHAKE_ANIMATION, result.ts);
            if (isNextDay) {
                SharePreferenceManager.saveVaule(mActivity, NO_SHAKE_ANIMATION, false);
                shakeTime = 0;
            }

            if (!StringUtil.isEmpty(serverPayload.pic) && serverPayload.pic.endsWith(".gif")) {
                return; //gif的情况下不展示摇晃动画
            }

            final AnimationSet animationSet = new AnimationSet(true);
            Animation shakeStart = AnimationUtils.loadAnimation(
                    mActivity, R.anim.shake_start);
            Animation shake = AnimationUtils.loadAnimation(
                    mActivity, R.anim.shake_animation);
            shake.setStartOffset(200);
            Animation shakeAgain = AnimationUtils.loadAnimation(
                    mActivity, R.anim.shake_again);
            shakeAgain.setStartOffset(600);
            Animation shakeLast = AnimationUtils.loadAnimation(
                    mActivity, R.anim.shake_animation);
            shakeLast.setStartOffset(1000);
            Animation shakeEnd = AnimationUtils.loadAnimation(
                    mActivity, R.anim.shake_end);
            shakeEnd.setStartOffset(1200);
            animationSet.
                    addAnimation(shakeStart);
            animationSet.addAnimation(shake);
            animationSet.addAnimation(shakeAgain);
            animationSet.addAnimation(shakeLast);
            animationSet.addAnimation(shakeEnd);

            final boolean noShake = SharePreferenceManager.getVaule(mActivity, NO_SHAKE_ANIMATION);
            LogUtils.d(TAG, "------------" + noShake + "");

            if (!noShake && shakeTime < 3) {
                if (shakeAnimationTimer == null) {
                    shakeAnimationTimer = new Timer();
                }
                shakeAnimationTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (mActivity != null) {
                            mActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!noShake && shakeTime < 3) { //防止前一个判断条件成立后timer一直执行
                                        if (isStart) {
                                            adContainer.clearAnimation();
                                            isStart = false;
                                        } else {
                                            adContainer.startAnimation(animationSet);
                                            isStart = true;
                                            shakeTime++;
                                        }
                                    } else {
                                        stopShakeAnimation();
                                    }
                                }
                            });
                        }
                    }
                }, 100, 1500);
            }
        }
    }

    private void stopShakeAnimation() {
        if (MoviesUtils.isProductKuaiKan() || MoviesUtils.isProductYsdq()) {
            if (adContainer != null) {
                adContainer.clearAnimation();
            }
            if (shakeAnimationTimer != null) {
                shakeAnimationTimer.cancel();
                shakeAnimationTimer = null;
            }
            SharePreferenceManager.saveVaule(mActivity, NO_SHAKE_ANIMATION, true);
        }
    }

    /**
     * 判断第二天的逻辑
     * @param lastTime 上次保存的时间戳
     * @param currentTime 当前时间戳
     * @return
     */
    private boolean isNextDayForShowShake(String lastTime, String currentTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yy/MM/dd");
        String[] lastTimeArr = sDateFormat.format(new Date(Long.valueOf(lastTime))).split("/");
        String[] currentTimeArr = sDateFormat.format(new Date(Long.valueOf(currentTime))).split("/");
        if (Integer.valueOf(lastTimeArr[0]) < Integer.valueOf(currentTimeArr[0])) {
            return true;
        }

        if (Integer.valueOf(lastTimeArr[1]) < Integer.valueOf(currentTimeArr[1])) {
            return true;
        }

        if (Integer.valueOf(lastTimeArr[2]) < Integer.valueOf(currentTimeArr[2])) {
            return true;
        }
        return false;
    }
    public void requestShakeAd(String adPlace) {
        if (MoviesUtils.isProductKuaiKan() || MoviesUtils.isProductYsdq()) {
            new RequestAdTask(MoviesApplication
                    .getInstance(), adPlace, new ShakeAdRequestResultListener()).start();
        }
    }

    private class ShakeAdRequestResultListener implements
            RequestResultListener<NewAdDataBean> {

        @Override
        public boolean onRequestFailed() {
            LogUtils.e(TAG, "!!!!!!!!!!!!!!请求广告数据失败!!!!!!!!!!!!!!");
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, NewAdDataBean result) {
            LogUtils.e(TAG, "!!!!!!!!!!!!!!AdDataBean：" + result);
            if (result != null) {
                showShakeAd(result);
                LogUtils.e(TAG, "!!!!请求广告数据成功!!!!");
            }
        }

        @Override
        public void onPreRequest() {

        }
    }

    private void umengServerShow() {
        HashMap<String, String> propertyMap = new HashMap<>();
        propertyMap.put("position", SelfDataConstant.AD_PO_DETAILCIRCLE);
        UmengEventPoster.doPost(UmengEventPoster.SERVER_SHOW, propertyMap);

        AdRequestStatis.selfReportAdShow(SelfDataConstant.AD_SERVER, SelfDataConstant.AD_PO_DETAILCIRCLE);
    }

    private void umengServerClick() {
        HashMap<String, String> propertyMap = new HashMap<>();
        propertyMap.put("position", SelfDataConstant.AD_PO_DETAILCIRCLE);
        UmengEventPoster.doPost(UmengEventPoster.SERVER_CLICK, propertyMap);

        AdRequestStatis.selfReportAdClick(SelfDataConstant.AD_SERVER, SelfDataConstant.AD_PO_DETAILCIRCLE);
    }
}
